﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows;
using System.IO;

namespace C9ShowNotesHelper.Utility
{
  public static class ScreenShot
  {
    //Based on http://www.dotnetspark.com/kb/1906-capture-screenshot-from-media-element-wpf.aspx

    public static byte[] GetScreenShot(this UIElement source, double scale, int quality)
    {
      JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
      jpgEncoder.QualityLevel = quality;
      jpgEncoder.Frames.Add(BitmapFrame.Create(GetScreenShotAsRenderTargetBitmap(source, scale, quality)));

      Byte[] imageArray;

      using (MemoryStream outputStream = new MemoryStream())
      {
        jpgEncoder.Save(outputStream);
        imageArray = outputStream.ToArray();
      }
      return imageArray;
    }

    public static RenderTargetBitmap GetScreenShotAsRenderTargetBitmap(this UIElement source, double scale, int quality)
    {
      double actualHeight = source.RenderSize.Height;
      double actualWidth = source.RenderSize.Width;
      double renderHeight = actualHeight * scale;
      double renderWidth = actualWidth * scale;

      RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth,
          (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
      VisualBrush sourceBrush = new VisualBrush(source);

      DrawingVisual drawingVisual = new DrawingVisual();
      DrawingContext drawingContext = drawingVisual.RenderOpen();

      using (drawingContext)
      {
        drawingContext.PushTransform(new ScaleTransform(scale, scale));
        drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0),
            new Point(actualWidth, actualHeight)));
      }
      renderTarget.Render(drawingVisual);

      return renderTarget;
    }
  }
}
